<?php

/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */


namespace app\api\controller\android\v13;

use think\Controller;
use app\api\model\Authority;
use  app\api\model\OrderModel;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Round;

class ReserveWage extends Controller
{
    protected $model;
    protected $us;

    public function _initialize()
    {
        $this->model = new Authority();
        $this->us    = $this->model->check(1);
    }


    /*
     * 列表项目利润
     */
    public function allProfit()
    {

        $param = Authority::param(['startTime', 'userId', 'type']);
        $arr   = date_parse_from_format('Y年m月', $param['startTime']);

        $time      = mktime(0, 0, 0, $arr['month'], 01, $arr['year']);
        $start     = strtotime(date('Y-m-01 00:00:00', $time)); //获取指定月份的第一天
        $end       = strtotime(date('Y-m-t 23:59:59', $time)); //获取指定月份的最后一天
        $orderList = [];
        if ($param['type'] == 1 && $param['userId'] != 0) {

            $chanel = db('user')->where(['status' => 0, 'user_id' => $param['userId']])->field('username,induction_time,user_id')->find();

            $orderDataSum = 0;
            $formula = '';
            if ($chanel['induction_time'] != 0) {
                if ($end < 1725120000) {
                    $orderData = $this->ReserveManager($chanel['induction_time'], $start, $end, 1, $chanel['user_id'], $chanel['username']);
                    $formula = '项目利润*基数*分红比例+代购利润*10%';
                } else {
                    $orderData = $this->NewReserveManager($chanel['induction_time'], $start, $end, 1, $chanel['user_id'], $chanel['username']);
                    $formula = '店长提成金额=结算合同金额-材料领用-费用报销-代购请款-师傅人工费-公司提成';
                }
            } else {
                $orderData = [
                    'CommissionAmount' => 0,
                    'ProjectProfit' => 0,
                    'oldSum' => 0,
                    'base' => 0,
                    'baseFormula' => 0,
                    'aBonus' => 0,
                    'agencyMoney' => 0,
                    'username' => $chanel['username'],
                    'userId' => $chanel['user_id'],
                ];
            }
            $orderDataSum +=  $orderData['CommissionAmount'] + $orderData['oldSum'];;
            $orderList[]  = [
                'username' => $orderData['username'],
                'userId' => $chanel['user_id'],
                'CommissionAmount' => (string)round($orderData['CommissionAmount'] + $orderData['oldSum'], 2),
                'formula' => $formula,
            ];

            r_date(['total' => (string)round($orderDataSum, 2), 'data' => $orderList], 200);
        }
        if ($param['userId'] == 0 && $param['type'] == 1) {

            $chanel       = db('user')->join('user_history', 'user_history.user_id=user.user_id', 'left')
                ->where('user_history.date_month', date('Y', $start) . date('m', $start))
                ->where('user_history.reserve', 2)
                ->where(['user.status' => 0, 'user.store_id' => $this->us['store_id']])
                ->field('username,induction_time,user.user_id')->select();
            $orderDataSum = 0;
            foreach ($chanel as $k => $l) {
                if ($l['induction_time'] != 0) {
                    $orderData = $this->ReserveManager($l['induction_time'], $start, $end, 1, $l['user_id'], $l['username']);
                    if ($end < 1725120000) {
                        $orderData = $this->ReserveManager($l['induction_time'], $start, $end, 1, $l['user_id'], $l['username']);
                    } else {
                        $orderData = $this->NewReserveManager($l['induction_time'], $start, $end, 1, $l['user_id'], $l['username']);
                    }
                } else {
                    $orderData = [
                        'CommissionAmount' => 0,
                        'ProjectProfit' => 0,
                        'oldSum' => 0,
                        'base' => 0,
                        'baseFormula' => 0,
                        'aBonus' => 0,
                        'agencyMoney' => 0,
                        'username' => $l['username'],
                        'userId' => $l['user_id'],
                    ];
                }
                $orderDataSum +=  $orderData['CommissionAmount'] + $orderData['oldSum'];;

                $orderList[] = [
                    'username' => $orderData['username'],
                    'userId' => $l['user_id'],
                    'CommissionAmount' => (string)round($orderData['CommissionAmount'] + $orderData['oldSum'], 2),
                    'formula' => '项目利润*基数*分红比例+代购利润*10%',
                ];
            }
            r_date(['total' => (string)round($orderDataSum, 2), 'data' => $orderList], 200);
        }
    }
     /*
    * 老板单个项目利润详情老数据结构
    */
    public function singleProfit()
    {
   
        $param = Authority::param(['startTime', 'userId']);
        $arr   = date_parse_from_format('Y年m月', $param['startTime']);

        $time = mktime(0, 0, 0, $arr['month'], 01, $arr['year']);

        $start = strtotime(date('Y-m-01 00:00:00', $time)); //获取指定月份的第一天
        $end   = strtotime(date('Y-m-t 23:59:59', $time)); //获取指定月份的最后一天

        $chanel = db('user')->where(['status' => 0, 'user_id' => $param['userId']])->field('username,induction_time')->find();
        if ($chanel['induction_time'] != 0) {
            if ($end < 1725120000) {
                $orderList = $this->ReserveManager($chanel['induction_time'], $start, $end, 1, $param['userId']);
            } else {
                ManagerCommission(date('Y-m-d',$end),$param['userId']);
                $orderList = $this->NewReserveManager($chanel['induction_time'], $start, $end, 1, $param['userId']);
            }
        } else {
            $orderList = [
                'CommissionAmount' => 0,
                'ProjectProfit' => 0,
                'ProjectProfitList' => [
                    'MainMaterialMoney' => 0,
                    'orderForRealityArtificial' => 0,
                    'materialUsage' => 0,
                    'companyCommission' => 0,
                    'reimbursement' => 0,
                    'money' => 0,
                    'discountRate' => 0,
                    'thisMonthTargetPerformance_title'=>'本月已接单目标业绩 ',
                    'thisMonthTargetPerformance' => 0, //本月已接单目标业绩
                    'onlineAchievement_title'=>'当月实际业绩',
                    'onlineAchievement' => 0, //查线当月实际业绩
                    'excessPerformanceReward_title'=>'超额业绩奖励',
                    'orderAttributionsAmount' => 0, //业绩目标超额奖金
                    'orderAttributionsAmount_title'=>'业绩目标超额奖金',
                    'excessPerformanceReward'=>0,//超额业绩奖励:
                    'orderAttributionsDeductAmount_title'=>'未达业绩目标扣除商机成本',
                    'orderAttributionsDeductAmount' => 0, //未达业绩目标扣除商机成本
                    'cost' => 0, //订单成本
                    'orderAttributions70Amount_title'=>'本次发放80%',
                    'order_attributions_70_amount' => 0,
                    'orderAttributions30Amount_title'=>"剩余20%延后发放",
                    'order_attributions_30_amount' => 0,
                    'companyCommission_year_title'=>"年度绩效金存入(1%)",
                    'companyCommission_year'=>0,
                    'delay_deduct_amount_title'=>'延期暂扣款',
                    'delay_deduct_amount'=>0,
                    'delay_tui_amount_title'=>'延期暂扣款退回',
                    'delay_tui_amount'=>0,
                    'he_title'=>'最终本月业绩工资获得',
                    'he_amount'=>'0',
                    'approval_schedule_liability_amount_title'=>"审批时责任划分承担金额",
                    'approval_schedule_liability_amount'=>0
                ],
                'base' => 0,
                'baseNumber' => 0,
                'aBonus' => 0,
                'orderId' => 0,
                'conversion' => 0,
                'oldSum' => 0,
                'OldList' => 0,
                'agencyMoney' => 0,
                'agencyMoneyProfit' => 0
            ];
        }
        $CommissionAmountFormula = '项目利润*基数*分红比例+代购合同分红';
        $profitCalculation = '';
        $orderOldState = 0;
        $ProjectProfitFormula = '完工完款金额-人工费-材料费-报销-订单费-主合同扣除师傅固定人工费(主合同金额*0.05)=项目利润';
        if ($end >= 1704038399) {
            $CommissionAmountFormula = '项目利润*基数*分红比例+代购合同分红';
            $ProjectProfitFormula = '完工完款金额-人工费-材料费-报销-订单费-主合同扣除师傅固定人工费(主合同金额*0.05)=项目利润';
            $profitCalculation = '主合同利润率大于等于40%时基数100%，主合同利润率大于等于35%小于40%时基数80%，主合同利润率大于等于30%小于35%时基数50%，主合同利润率小于30%时基数0%';
            $orderOldState = 0;
        }
        if ($start >= 1725120000) {
            $CommissionAmountFormula = '店长提成金额=结算合同金额-材料领用-费用报销-代购请款-师傅人工费-公司提成';
            $ProjectProfitFormula = '';
            $profitCalculation = '';
            $orderOldState = 1;
        }
        $describe='';
        if($start>1725120000){
            $describe='计算逻辑：<br/>
■完工完款金额(含代购)：按合同结算时间统计本月合同金额汇总金额。<br/>
■人工费：主合同结算订单的直接成本项，按当月结算的订单里，通过审核的人工费数据合计后金额。<br/>
■材料金额：主合同结算订单的直接成本项，按当月结算的订单里，通过审核的材料费用数据合计后金额。<br/>
■报销金额(含代购)：按当月结算的订单里，使用报销产生的金额+代购主材请款的金额。<br/>
■公司计提金额：合同计提金额=（合同结算金额+超限优惠金额）x 计提比例<br/>
■超额业绩奖励本次发放80%：每月业绩超额奖金当月只发80%，剩余20%累计到超额业绩奖金池，年底进行核算。详细说明：（1）C端商机成交率25%及以上，同时商机量10单以上，参与超额奖励；成交率以派单时间在当月的C端商机为分母，以正签时间在当月的C端订单为分子进行计算；商机量以派单时间在当月的C端商机求和进行计算.（2）新入职店长前5单不计入考核（目标业绩和成本定价），首月按60%计算（不满15天，次月算首月），次月按80%计算；由于2025年2月10日前做活动，之前的C端订单不计算目标业绩和商机成本。<br/>
■未达业绩目标扣除商机成本 ：C端承担商机成本，是按规则扣除前期累积金额剩余部分（整个暂未发的20%部分），在当月提成合计里扣除。<br/>
■年度绩效金存入(1%)：店长年度绩效金为结算金额1%的金额累计，满2万后，超额部分按制度依次发放前期累积金额。<br/>
■延期暂扣款：因项目延期导致的暂缓发放的提成。<br/>
■延期暂扣款退回：延期暂缓发放的提成对应的订单完结后，返回的提成。<br/>
■审批时责任划分承担金额：部分审批中，判责时确认的成本承担人，累计个人当月所有审核中需要担责的成本金额。';
        
        }
        r_date([
            'CommissionAmount' => $orderList['CommissionAmount'],
            'CommissionAmountFormula' => $CommissionAmountFormula,
            'ProjectProfit' => $orderList['ProjectProfit'],
            'describe'=>$describe,
            'ProjectProfitList' => [
                'MainMaterialMoney' => $orderList['ProjectProfitList']['MainMaterialMoney']>0?'+'.$orderList['ProjectProfitList']['MainMaterialMoney']:$orderList['ProjectProfitList']['MainMaterialMoney'],
                'orderForRealityArtificial' => $orderList['ProjectProfitList']['orderForRealityArtificial']>0?'-'.$orderList['ProjectProfitList']['orderForRealityArtificial']:$orderList['ProjectProfitList']['orderForRealityArtificial'],
                'materialUsage' => $orderList['ProjectProfitList']['materialUsage']>0?'-'.$orderList['ProjectProfitList']['materialUsage']:$orderList['ProjectProfitList']['materialUsage'],
                'companyCommission' => $orderList['ProjectProfitList']['companyCommission']>0?'-'.$orderList['ProjectProfitList']['companyCommission']:$orderList['ProjectProfitList']['companyCommission'],
                'reimbursement' => $orderList['ProjectProfitList']['reimbursement']>0?'-'.$orderList['ProjectProfitList']['reimbursement']:$orderList['ProjectProfitList']['reimbursement'],
                'money' => $orderList['ProjectProfitList']['money']>0?'-'.$orderList['ProjectProfitList']['money']:$orderList['ProjectProfitList']['money'],
                'discountRate' => $orderList['ProjectProfitList']['discountRate']>0?'-'.$orderList['ProjectProfitList']['discountRate']:$orderList['ProjectProfitList']['discountRate'],
                'thisMonthTargetPerformance_title'=>'本月已接单目标业绩 ',
                'thisMonthTargetPerformance' => $orderList['ProjectProfitList']['thisMonthTargetPerformance'], //本月已接单目标业绩
                'onlineAchievement_title'=>'当月实际业绩',
                'onlineAchievement' =>  $orderList['ProjectProfitList']['onlineAchievement'], //查线当月实际业绩
                'excessPerformanceReward_title'=>'超额业绩奖励',
                'excessPerformanceReward'=>$orderList['ProjectProfitList']['orderAttributionsAmount'],//超额业绩奖励:
                'orderAttributionsAmount_title'=>'业绩目标超额奖金',
                'orderAttributionsAmount' =>  $orderList['ProjectProfitList']['onlineAchievement']-$orderList['ProjectProfitList']['thisMonthTargetPerformance'], //业绩目标超额奖金
                'orderAttributionsDeductAmount_title'=>'未达业绩目标扣除商机成本',
                'orderAttributionsDeductAmount' =>  $orderList['ProjectProfitList']['orderAttributionsDeductAmount']>0?'-'.$orderList['ProjectProfitList']['orderAttributionsDeductAmount']:$orderList['ProjectProfitList']['orderAttributionsDeductAmount'], //未达业绩目标扣除商机成本
                'cost' => $orderList['ProjectProfitList']['cost'], //订单成本
                'orderAttributions70Amount_title'=>'本次发放80%',
                'orderAttributions70Amount' => $orderList['ProjectProfitList']['order_attributions_70_amount']>0?'+'.$orderList['ProjectProfitList']['order_attributions_70_amount']:$orderList['ProjectProfitList']['order_attributions_70_amount'],
                'orderAttributions30Amount_title'=>"剩余20%延后发放",
                'orderAttributions30Amount' =>$orderList['ProjectProfitList']['order_attributions_30_amount'],
                'companyCommission_year_title'=>"年度绩效金存入(1%)",
                'companyCommission_year'=>$orderList['ProjectProfitList']['companyCommission_year']>0?'-'.$orderList['ProjectProfitList']['companyCommission_year']:$orderList['ProjectProfitList']['companyCommission_year'],
                'delay_deduct_amount_title'=>'延期暂扣款',
                'delay_deduct_amount'=>$orderList['ProjectProfitList']['delay_deduct_amount']>0?'-'.$orderList['ProjectProfitList']['delay_deduct_amount']:$orderList['ProjectProfitList']['delay_deduct_amount'],
                'delay_tui_amount_title'=>'延期暂扣款退回',
                'delay_tui_amount'=>$orderList['ProjectProfitList']['delay_tui_amount']>0?'+'.$orderList['ProjectProfitList']['delay_tui_amount']:$orderList['ProjectProfitList']['delay_tui_amount'],
                'he_title'=>'最终本月业绩工资获得',
                'he_amount'=>$orderList['CommissionAmount'],
                'approval_schedule_liability_amount_title'=>"审批时责任划分承担金额",
                'approval_schedule_liability_amount'=>$orderList['ProjectProfitList']['approval_schedule_liability_amount']>0?'-'.$orderList['ProjectProfitList']['approval_schedule_liability_amount']:$orderList['ProjectProfitList']['approval_schedule_liability_amount']
            ],
            'ProjectProfitFormula' => $ProjectProfitFormula,
            'base' => $orderList['base'] * 100,
            'baseNumber' => number_format($orderList['baseNumber'] * 100, 2),
            'profitCalculation' => $profitCalculation,

            //            'baseFormula' => '项目利润(不扣减订单费)/完工完款金额',
            'baseFormula' => '主合同利润率=（完工完款主合同金额-人工费-材料费-报销[不减订单费]）/完工完款主合同金额',
            'aBonus' => $orderList['aBonus'] * 100,
            'conversion' => $orderList['conversion'] * 100,
            'dividendAlgorithm' => '分红比例15%=基数100%乘以15%，分红比例12%=基数80%乘以15%，分红比例7.5%=基数50%乘以15%',
            'aBonusFormula' => '取消',
            'agencyMoney' => $orderList['agencyMoney'],
            'agencyMoneyProfit' => $orderList['agencyMoneyProfit'],
            'agencyMoneyFormula' => '按照代购合同所有利润的10%分红',
            'username' => $chanel['username'],
            'orderId' => empty($orderList['orderId'])?-1:$orderList['orderId'],
            'oldSum' => $orderList['oldSum'],
            'orderOldState' => $orderOldState,
            'OldList' => empty($orderList['oldList']) ? null : [
                'CommissionAmount' => $orderList['oldList'][0]['CommissionAmount'],
                'CommissionAmountFormula' => '项目利润*基数*分红比例+代购合同分红',
                'ProjectProfit' => $orderList['oldList'][0]['ProjectProfit'],
                'ProjectProfitList' => [
                    'MainMaterialMoney' => $orderList['oldList'][0]['ProjectProfitList']['MainMaterialMoney'],
                    'orderForRealityArtificial' => $orderList['oldList'][0]['ProjectProfitList']['orderForRealityArtificial'],
                    'materialUsage' => $orderList['oldList'][0]['ProjectProfitList']['materialUsage'],
                    'reimbursement' => $orderList['oldList'][0]['ProjectProfitList']['reimbursement'],
                    'money' => $orderList['oldList'][0]['ProjectProfitList']['money'],
                    'discountRate' => $orderList['oldList'][0]['ProjectProfitList']['discountRate']
                ],
                'ProjectProfitFormula' => '完工完款金额-人工费-材料费-报销-订单费=项目利润',
                'base' => $orderList['oldList'][0]['base'] * 100,
                'baseNumber' => number_format($orderList['oldList'][0]['baseNumber'] * 100, 2),
                'profitCalculation' => '主合同利润率大于等于45%时基数100%，主合同利润率大于等于40%小于45%时基数80%，主合同利润率大于等于35%小于40%时基数50%，主合同利润率小于35%时基数0%',
//            'baseFormula' => '项目利润(不扣减订单费)/完工完款金额',
                'baseFormula' => '主合同利润率=（完工完款主合同金额-人工费-材料费-报销[不减订单费]）/完工完款主合同金额',
                'aBonus' => $orderList['oldList'][0]['aBonus'] * 100,
                'conversion' => $orderList['oldList'][0]['conversion'] * 100,
                'dividendAlgorithm' => '分红比例15%=基数100%乘以15%，分红比例12%=基数80%乘以15%，分红比例7.5%=基数50%乘以15%',
                'aBonusFormula' => '取消',
                'agencyMoney' => $orderList['oldList'][0]['agencyMoney'],
                'agencyMoneyProfit' => $orderList['oldList'][0]['agencyMoneyProfit'],
                'agencyMoneyFormula' => '按照代购合同所有利润的10%分红',
                'username' => $chanel['username'],
                'orderId' => empty($orderList['oldList'][0]['orderId'])?-1:$orderList['oldList'][0]['orderId'],
            ]
        ], 200);
    }

    /*
    * 新版单个项目利润详情结构发生变化
    */
    public function splittingDetails()
    {

        $param = Authority::param(['startTime', 'userId']);
        $arr   = date_parse_from_format('Y年m月', $param['startTime']);

        $time = mktime(0, 0, 0, $arr['month'], 01, $arr['year']);

        $start = strtotime(date('Y-m-01 00:00:00', $time)); //获取指定月份的第一天
        $end   = strtotime(date('Y-m-t 23:59:59', $time)); //获取指定月份的最后一天

        $chanel = db('user')->where(['status' => 0, 'user_id' => $param['userId']])->field('username,induction_time')->find();
        if ($chanel['induction_time'] != 0) {
            if ($end < 1725120000) {
                $orderList = $this->ReserveManager($chanel['induction_time'], $start, $end, 1, $param['userId']);
            } else {
                ManagerCommission(date('Y-m-d', $end), $param['userId']);
                $orderList = $this->NewReserveManager($chanel['induction_time'], $start, $end, 1, $param['userId']);
            }
        } else {
            $orderList = [
                'CommissionAmount' => 0,
                'ProjectProfit' => 0,
                'ProjectProfitList' => null,
                'splittingDetails' =>
                [
                    [
                        'title' => "完工完款金额（含代购不含直售）",

                        'money' => 0,
                        'type' => 1,
                    ],

                    [
                        'title' => "人工费",
                        'money' => 0,
                        'type' => 2
                    ],
                    [
                        'title' => "材料金额",
                        'money' => 0,
                        'type' => 3
                    ],
                    [
                        'title' => "报销金额（含代购）",
                        'money' => 0,
                        'type' => 4
                    ],
                    [
                        'title' => "公司计提金额",
                        'money' => 0,
                        'type' => 5
                    ],
                    [

                        'title' => '直售产品清单提成',
                        'money' => 0,
                        'type' => 6,
                    ],
                    [

                        'title' => '直售清单成本冲抵',
                        'money' => 0,
                        'type' => 6,
                    ],


                    [

                        'title' => '超额业绩奖励本次发放80%',
                        'money' => 0,
                        'type' => 6,
                    ],
                    [
                        'title' => '未达业绩目标扣除商机成本',
                        'money' =>  0,
                        'type' => 7,
                    ],
                    [

                        'title' => "年度绩效金存入(1%)",
                        'money' => 0,
                        'type' => 8
                    ],
                    [
                        'title' => '延期暂扣款',
                        'money' => 0,
                        'type' => 9
                    ],
                    [

                        'title' => '延期暂扣款退回',
                        'money' => 0,
                        'type' => 9
                    ],

                    [
                        'title' => "审批时责任划分承担金额",
                        'money' => 0,
                        'type' => 11
                    ],
                    [
                        'title' => '最终本月业绩工资获得',
                        'money' => 0,
                        'type' => 0
                    ]

                ],
                'base' => 0,
                'baseNumber' => 0,
                'aBonus' => 0,
                'orderId' => 0,
                'conversion' => 0,
                'oldSum' => 0,
                'OldList' => 0,
                'agencyMoney' => 0,
                'agencyMoneyProfit' => 0
            ];
        }
        $CommissionAmountFormula = '项目利润*基数*分红比例+代购合同分红';
        $profitCalculation = '';
        $orderOldState = 0;
        $ProjectProfitFormula = '完工完款金额-人工费-材料费-报销-订单费-主合同扣除师傅固定人工费(主合同金额*0.05)=项目利润';
        if ($end >= 1704038399) {
            $CommissionAmountFormula = '项目利润*基数*分红比例+代购合同分红';
            $ProjectProfitFormula = '完工完款金额-人工费-材料费-报销-订单费-主合同扣除师傅固定人工费(主合同金额*0.05)=项目利润';
            $profitCalculation = '主合同利润率大于等于40%时基数100%，主合同利润率大于等于35%小于40%时基数80%，主合同利润率大于等于30%小于35%时基数50%，主合同利润率小于30%时基数0%';
            $orderOldState = 0;
        }
        if ($start >= 1725120000) {
            $CommissionAmountFormula = '店长提成金额=结算合同金额-材料领用-费用报销-代购请款-师傅人工费-公司提成';
            $ProjectProfitFormula = '';
            $profitCalculation = '';
            $orderOldState = 1;
        }
        $describe = '';
        if ($start > 1725120000) {
            $describe = '计算逻辑：<br/>
■完工完款金额(含代购)：按合同结算时间统计本月合同金额汇总金额。<br/>
■人工费：主合同结算订单的直接成本项，按当月结算的订单里，通过审核的人工费数据合计后金额。<br/>
■材料金额：主合同结算订单的直接成本项，按当月结算的订单里，通过审核的材料费用数据合计后金额。<br/>
■报销金额(含代购)：按当月结算的订单里，使用报销产生的金额+代购主材请款的金额。<br/>
■公司计提金额：合同计提金额=（合同结算金额+超限优惠金额）x 计提比例<br/>
■超额业绩奖励本次发放80%：每月业绩超额奖金当月只发80%，剩余20%累计到超额业绩奖金池，年底进行核算。详细说明：（1）C端商机成交率25%及以上，同时商机量10单以上，参与超额奖励；成交率以派单时间在当月的C端商机为分母，以正签时间在当月的C端订单为分子进行计算；商机量以派单时间在当月的C端商机求和进行计算.（2）新入职店长前5单不计入考核（目标业绩和成本定价），首月按60%计算（不满15天，次月算首月），次月按80%计算；由于2025年2月10日前做活动，之前的C端订单不计算目标业绩和商机成本。<br/>
■未达业绩目标扣除商机成本 ：C端承担商机成本，是按规则扣除前期累积金额剩余部分（整个暂未发的20%部分），在当月提成合计里扣除。<br/>
■年度绩效金存入(1%)：店长年度绩效金为结算金额1%的金额累计，满2万后，超额部分按制度依次发放前期累积金额。<br/>
■延期暂扣款：因项目延期导致的暂缓发放的提成。<br/>
■延期暂扣款退回：延期暂缓发放的提成对应的订单完结后，返回的提成。<br/>
■审批时责任划分承担金额：部分审批中，判责时确认的成本承担人，累计个人当月所有审核中需要担责的成本金额。';
        }

        r_date([
            'CommissionAmount' => $orderList['CommissionAmount'],
            'CommissionAmountFormula' => $CommissionAmountFormula,
            'ProjectProfit' => $orderList['ProjectProfit'],
            'describe' => $describe,
            'ProjectProfitList' => null,
            'splittingDetails' => [
                [
                    'title' => "完工完款金额（含代购不含直售）",
                    'money' => $orderList['ProjectProfitList']['MainMaterialMoney'] > 0 ? '+' . $orderList['ProjectProfitList']['MainMaterialMoney'] : $orderList['ProjectProfitList']['MainMaterialMoney'],
                    "prompt" => "不含直售",
                    'type' => 1,
                    'isRed' => 0,
                ],

                [
                    'title' => "人工费",
                    'money' => $orderList['ProjectProfitList']['orderForRealityArtificial'] > 0 ? '-' . $orderList['ProjectProfitList']['orderForRealityArtificial'] : $orderList['ProjectProfitList']['orderForRealityArtificial'],
                    'type' => 2,
                    'isRed' => 0,
                ],
                [
                    'title' => "材料金额",
                    'money' => $orderList['ProjectProfitList']['materialUsage'] > 0 ? '-' . $orderList['ProjectProfitList']['materialUsage'] : $orderList['ProjectProfitList']['materialUsage'],
                    'type' => 3,
                    'isRed' => 0,
                ],
                [
                    'title' => "报销金额（含代购）",
                    'money' => $orderList['ProjectProfitList']['reimbursement'] > 0 ? '-' . $orderList['ProjectProfitList']['reimbursement'] : $orderList['ProjectProfitList']['reimbursement'],
                    'type' => 4
                ],
                [
                    'title' => "公司计提金额",
                    'money' => $orderList['ProjectProfitList']['companyCommission'] > 0 ? '-' . $orderList['ProjectProfitList']['companyCommission'] : $orderList['ProjectProfitList']['companyCommission'],
                    'type' => 5,
                    'isRed' => 0,
                ],
                [

                    'title' => '直售产品清单提成',
                    'money' => $orderList['ProjectProfitList']['direct_commission_rati'] > 0 ? '+' . $orderList['ProjectProfitList']['direct_commission_rati'] : $orderList['ProjectProfitList']['direct_commission_rati'],
                     "prompt" => "",
                    'type' => 6,
                     'isRed' => 0,
                     'data'
                ],
                [

                    'title' => '直售清单成本冲抵',
                    'money' => $orderList['ProjectProfitList']['direct_shopowner_profit']??0 > 0 ? '+' . $orderList['ProjectProfitList']['direct_shopowner_profit'] : $orderList['ProjectProfitList']['direct_shopowner_profit'],
                    "prompt" => "直售成本为固定金额，成交后会直接扣减，但主材派单或人工费中仍然会体现成本支出，所以为了避免算2次成本，这里会冲抵掉主材或人工费中扣减的金额。",
                    'type' => 6,
                ],

                [

                    'title' => '超额业绩奖励本次发放80%',
                    'money' => $orderList['ProjectProfitList']['order_attributions_70_amount'] > 0 ? '+' . $orderList['ProjectProfitList']['order_attributions_70_amount'] : $orderList['ProjectProfitList']['order_attributions_70_amount'],
                    'type' => 6,
                    'isRed' => 0,
                ],
                [
                    'title' => '未达业绩目标扣除商机成本',
                    'money' =>  $orderList['ProjectProfitList']['orderAttributionsDeductAmount'] > 0 ? '-' . $orderList['ProjectProfitList']['orderAttributionsDeductAmount'] : $orderList['ProjectProfitList']['orderAttributionsDeductAmount'], //未达业绩目标扣除商机成本
                    'type' => 7,
                    'isRed' => 0,
                ],
                [

                    'title' => "年度绩效金存入(1%)",
                    'money' => $orderList['ProjectProfitList']['companyCommission_year'] > 0 ? '-' . $orderList['ProjectProfitList']['companyCommission_year'] : $orderList['ProjectProfitList']['companyCommission_year'],
                    'type' => 8,
                    'isRed' => 0,
                ],
                [
                    'title' => '延期暂扣款',
                    'money' => $orderList['ProjectProfitList']['delay_deduct_amount'] > 0 ? '-' . $orderList['ProjectProfitList']['delay_deduct_amount'] : $orderList['ProjectProfitList']['delay_deduct_amount'],
                    'type' => 9,
                    'isRed' => 0,
                ],
                [

                    'title' => '延期暂扣款退回',
                    'money' => $orderList['ProjectProfitList']['delay_tui_amount'] > 0 ? '+' . $orderList['ProjectProfitList']['delay_tui_amount'] : $orderList['ProjectProfitList']['delay_tui_amount'],
                    'type' => 9,
                    'isRed' => 0,
                ],

                [
                    'title' => "审批时责任划分承担金额",
                    'money' => $orderList['ProjectProfitList']['approval_schedule_liability_amount'] > 0 ? '-' . $orderList['ProjectProfitList']['approval_schedule_liability_amount'] : $orderList['ProjectProfitList']['approval_schedule_liability_amount'],
                    'type' => 11,
                    'isRed' => 0,
                ],
                [
                    'title' => '最终本月业绩工资获得',
                    'money' => $orderList['CommissionAmount'],
                    'type' => 0,
                    'isRed' => 1,
                ],
            ],
            'ProjectProfitFormula' => $ProjectProfitFormula,
            'base' => $orderList['base'] * 100,
            'baseNumber' => number_format($orderList['baseNumber'] * 100, 2),
            'profitCalculation' => $profitCalculation,

            //            'baseFormula' => '项目利润(不扣减订单费)/完工完款金额',
            'baseFormula' => '主合同利润率=（完工完款主合同金额-人工费-材料费-报销[不减订单费]）/完工完款主合同金额',
            'aBonus' => $orderList['aBonus'] * 100,
            'conversion' => $orderList['conversion'] * 100,
            'dividendAlgorithm' => '分红比例15%=基数100%乘以15%，分红比例12%=基数80%乘以15%，分红比例7.5%=基数50%乘以15%',
            'aBonusFormula' => '取消',
            'agencyMoney' => $orderList['agencyMoney'],
            'agencyMoneyProfit' => $orderList['agencyMoneyProfit'],
            'agencyMoneyFormula' => '按照代购合同所有利润的10%分红',
            'username' => $chanel['username'],
            'orderId' => empty($orderList['orderId']) ? -1 : $orderList['orderId'],
            'oldSum' => $orderList['oldSum'],
            'orderOldState' => $orderOldState,
            'OldList' => empty($orderList['oldList']) ? null : [
                'CommissionAmount' => $orderList['oldList'][0]['CommissionAmount'],
                'CommissionAmountFormula' => '项目利润*基数*分红比例+代购合同分红',
                'ProjectProfit' => $orderList['oldList'][0]['ProjectProfit'],
                'ProjectProfitList' => [
                    'MainMaterialMoney' => $orderList['oldList'][0]['ProjectProfitList']['MainMaterialMoney'],
                    'orderForRealityArtificial' => $orderList['oldList'][0]['ProjectProfitList']['orderForRealityArtificial'],
                    'materialUsage' => $orderList['oldList'][0]['ProjectProfitList']['materialUsage'],
                    'reimbursement' => $orderList['oldList'][0]['ProjectProfitList']['reimbursement'],
                    'money' => $orderList['oldList'][0]['ProjectProfitList']['money'],
                    'discountRate' => $orderList['oldList'][0]['ProjectProfitList']['discountRate']
                ],
                'ProjectProfitFormula' => '完工完款金额-人工费-材料费-报销-订单费=项目利润',
                'base' => $orderList['oldList'][0]['base'] * 100,
                'baseNumber' => number_format($orderList['oldList'][0]['baseNumber'] * 100, 2),
                'profitCalculation' => '主合同利润率大于等于45%时基数100%，主合同利润率大于等于40%小于45%时基数80%，主合同利润率大于等于35%小于40%时基数50%，主合同利润率小于35%时基数0%',
                //            'baseFormula' => '项目利润(不扣减订单费)/完工完款金额',
                'baseFormula' => '主合同利润率=（完工完款主合同金额-人工费-材料费-报销[不减订单费]）/完工完款主合同金额',
                'aBonus' => $orderList['oldList'][0]['aBonus'] * 100,
                'conversion' => $orderList['oldList'][0]['conversion'] * 100,
                'dividendAlgorithm' => '分红比例15%=基数100%乘以15%，分红比例12%=基数80%乘以15%，分红比例7.5%=基数50%乘以15%',
                'aBonusFormula' => '取消',
                'agencyMoney' => $orderList['oldList'][0]['agencyMoney'],
                'agencyMoneyProfit' => $orderList['oldList'][0]['agencyMoneyProfit'],
                'agencyMoneyFormula' => '按照代购合同所有利润的10%分红',
                'username' => $chanel['username'],
                'orderId' => empty($orderList['oldList'][0]['orderId']) ? -1 : $orderList['oldList'][0]['orderId'],
            ]
        ], 200);
    }


    /*
     * 分红比例
     */
    public static function aBonus($induction_time, $userId, $start, $end, $type)
    {
        $order = db('order')->join('contract', 'contract.orders_id=order.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left');

        if ($type == 1) {
            $order->where('order.assignor', $userId);
        } else {
            $order->where('user.store_id', $userId);
        }
        if ($induction_time > $start) {
            $start = $induction_time;
        }
        $order = $order->whereBetween('contract.con_time', [$start, $end])->field('order.channel_id,order.state')->select();


        $SignedQuantity = [];
        $ActivityOrder  = [];
        foreach ($order as $item) {
            if ($item['state'] > 3) {
                $SignedQuantity[] = $item;
            }
            if ($item['channel_id'] == 27 || $item['channel_id'] == 28) {
                $ActivityOrder[] = $item;
            }
        }

        if (count($SignedQuantity) > 0) {
            $aBonus = count($ActivityOrder) / count($SignedQuantity);
        } else {
            $aBonus = 0;
        }

        if (1638288000 <= $start && $end <= 1646063999) {
            $conversion = 0.2;
        } else {
            if ($aBonus >= 0.35) {
                $conversion = 0.2;
            } else {
                $conversion = 0.15;
            }
        }
        if (1640966400 <= $start) {
            $conversion = 0.15;
        }
        return ['conversion' => sprintf('%.2f', $conversion), 'aBonus' => round($aBonus, 4)];
    }

    /*
     * 储备店长总数据
     */
    public function ReserveManager($induction_time, $start, $end, $type, $id, $username = '')
    {
        $sysConfig = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->where('statusss', 1)->value('valuess');
        $order     = \db('order')
            ->field('order_aggregate.reimbursement_price as reimbursement,order_aggregate.reimbursement_agent_price as settlementReimbursement,order_aggregate.material_price as material_usage,order.order_id,order.cleared_time,order.settlement_time,order.created_time,order.notcost_time, order_aggregate.master_price as capitalPersonal,contract.con_time, order_aggregate.material_agent_price as settlementMaterial_usage')
            ->join('user',  'user.user_id=order.assignor', 'left')
            ->join('contract', 'contract.orders_id=order.order_id', 'left')
            ->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left');
        if ($type == 1) {
            $order->where('user.user_id', $id);
        } elseif ($type == 2) {
            $order->where('user.store_id', $id);
        }
        if ($induction_time > $start) {
            $start = $induction_time;
        }
        $orderList = $order->where(function ($quer) use ($start, $end) {
            $quer->whereBetween('order.cleared_time', [$start, $end])->whereOr('order.settlement_time', 'between', [$start, $end]);
        })->where('contract.con_time', '>', $induction_time)->where('user.ce', '<>', 2)->group('order.order_id')->select();

        $order_system_clear = db('order_system_clear', config('database.zong'))->whereIn('clear_action', [1, 2, 3])->select();
        $clearedOrder       = [];
        $settlementOrder    = [];
        $order_system_clear_main = [];
        $order_system_clear_agent = [];
        foreach ($order_system_clear as $value) {
            if ($value['clear_action'] == 1 || $value['clear_action'] == 3) {
                $order_system_clear_main[] = $value['order_id'];
            }
            if ($value['clear_action'] == 2 || $value['clear_action'] == 3) {
                $order_system_clear_agent[] = $value['order_id'];
            }
        }
        //2023年签约的主合同订单
        $oldClearedOrderMan = [];
        //2023年签约的代购合同订单
        $oldClearedOrderAgent = [];
        //2024年签约的主合同订单
        $newOrderIdMan = [];
        //2024年签约的代购合同订单
        $newOrderIdAgent = [];
        foreach ($orderList as $item) {
            if ((!empty($item['cleared_time']) && ($start <= $item['cleared_time'] && $end >= $item['cleared_time']) && !in_array($item['order_id'], $order_system_clear_main)) && $item['con_time'] <= 1704038399) {
                $oldClearedOrderMan[] = $item;
            }
            if ((!empty($item['settlement_time']) && ($start <= $item['settlement_time'] && $end >= $item['settlement_time']) && !in_array($item['order_id'], $order_system_clear_agent)) && $item['con_time'] <= 1704038399) {
                $oldClearedOrderAgent[] = $item;
            }
            if ((!empty($item['cleared_time']) && ($start <= $item['cleared_time'] && $end >= $item['cleared_time']) && !in_array($item['order_id'], $order_system_clear_main)) && $item['con_time'] > 1704038399) {
                $newOrderIdMan[] = $item['order_id'];
            }
            if ((!empty($item['settlement_time']) && ($start <= $item['settlement_time'] && $end >= $item['settlement_time']) && !in_array($item['order_id'], $order_system_clear_agent)) && $item['con_time'] > 1704038399) {
                $newOrderIdAgent[] = $item['order_id'];;
            }
            if (!empty($item['cleared_time']) && ($start <= $item['cleared_time'] && $end >= $item['cleared_time']) && !in_array($item['order_id'], $order_system_clear_main)) {
                $clearedOrder[] = $item;
            }
            if (!empty($item['settlement_time']) && ($start <= $item['settlement_time'] && $end >= $item['settlement_time']) && !in_array($item['order_id'], $order_system_clear_agent)) {
                $settlementOrder[] = $item;
            }
        }

        $OrderFee  = [];
        if ($end <= 1704038399) {
            $count = db('order')
                ->join('user', 'user.user_id=order.assignor', 'left')
                ->join('order_setting', 'order_setting.order_id=order.order_id', 'left')
                ->where('user.ce', '<>', 2);
            if ($type == 1) {
                $count->where('user.user_id', $id);
            } elseif ($type == 2) {
                $count->where('user.store_id', $id);
                $count->where('user.reserve', 2);
            }

            $userList       = [];
            $orderListMoney = $count->whereBetween('order.created_time', [$start, $end])
                ->where('order.created_time > user.induction_time')
                ->field('order.created_time,order.notcost_time,order_setting.order_fee,user.user_id')
                ->select();
            foreach ($orderListMoney as $value) {
                if (($value['notcost_time'] == 'null' || $value['notcost_time'] == 0) && $value['created_time'] >= 1643644800) {
                    $OrderFee[] = $value;
                };

                $userList[] = $value['user_id'];
            }
        } else {
            $count = db('order')
                ->join('user', 'user.user_id=order.assignor', 'left')
                ->join('order_times', 'order_times.order_id=order.order_id', 'left')
                ->join('order_setting', 'order_setting.order_id=order.order_id', 'left')
                ->where('user.ce', '<>', 2);
            if ($type == 1) {
                $count->where('user.user_id', $id);
            } elseif ($type == 2) {
                $count->where('user.store_id', $id);
                $count->where('user.reserve', 2);
            }

            $userList       = [];
            $orderListMoney = $count->whereBetween('order_times.dispatch_time', [$start, $end])
                ->where('order_times.dispatch_time > user.induction_time')
                ->field('order_times.dispatch_time,order.notcost_time,order_setting.order_fee,user.user_id')
                ->select();
            foreach ($orderListMoney as $value) {
                if (($value['notcost_time'] == 'null' || $value['notcost_time'] == 0) && $value['dispatch_time'] > 1704038399) {
                    $OrderFee[] = $value;
                };
                $userList[] = $value['user_id'];
            }
        }

        $userList           = array_unique($userList);
        $order_id           = array_column($clearedOrder, 'order_id');
        $settlementOrder_id = array_column($settlementOrder, 'order_id');
        // 完款金额
        $EndOfPayment           = (new OrderModel())->TotalProfit($order_id);
        $settlementEndOfPayment = (new OrderModel())->TotalProfit($settlementOrder_id);

        //2023年签约的金额
        $oldClearedOrderManOrderId = array_column($oldClearedOrderMan, 'order_id');
        $oldClearedOrderAgentOrderId = array_column($oldClearedOrderAgent, 'order_id');
        $OldEndOfPaymentMan = (new OrderModel())->TotalProfit($oldClearedOrderManOrderId);
        $OldEndOfPaymentAgent = (new OrderModel())->TotalProfit($oldClearedOrderAgentOrderId);

        //订单费
        $money                            = sprintf('%.2f', array_sum(array_column($OrderFee, 'order_fee')));
        $achievement_order_fee_discount   = \db('config')->where('name', 'achievement_order_fee_discount')->value('content');
        $turnover_rate_order_fee_discount = \db('config')->where('name', 'turnover_rate_order_fee_discount')->value('content');
        $achievement_order_fee_discount   = json_decode($achievement_order_fee_discount, true);
        $turnover_rate_order_fee_discount = json_decode($turnover_rate_order_fee_discount, true);
        $userId = $this->us['user_id'];
        if ($type == 1) {
            $userId = $id;
        }
        $signing     = $this->RCalculatePerformance($userId, $start, $end, 2);
        $achievement = 0;
        $turnover    = 0;
        foreach ($achievement_order_fee_discount as $item) {
            if ($item['begin'] <= $signing && $item['end'] > $signing) {
                $achievement = $item['value'];
            }
        }
        if (!empty($userList)) {
            $conversion = (new WorkBench())->Conversion($start, $end, $userList, 3);
            $conversion = empty($conversion) ? 0 : $conversion[0]['value'] / 100;
            foreach ($turnover_rate_order_fee_discount as $item) {
                if ($item['begin'] <= $conversion && $item['end'] > $conversion) {
                    $turnover = $item['value'];
                }
            }
        }
        //订单会折扣了率
        $discountRate = $achievement;
        if ($achievement != 0 && $turnover != 0) {
            if ($achievement  > $turnover) {
                $discountRate = $turnover;
            }
        }
        if ($achievement == 0 && $turnover != 0) {
            $discountRate = $turnover;
        }

        if ($achievement == 0 && $turnover == 0) {
            $discountRate = 0.7;
        }



        //2023年结算的
        //材料报销
        $OldMaterial_usage = sprintf('%.2f', array_sum(array_column($oldClearedOrderMan, 'material_usage')));
        //报销费用
        $OldReimbursement            = sprintf('%.2f', array_sum(array_column($oldClearedOrderMan, 'reimbursement')));
        $OldSettlementReimbursement  = sprintf('%.2f', array_sum(array_column($oldClearedOrderAgent, 'settlementReimbursement')));
        $OldSettlementMaterial_usage = sprintf('%.2f', array_sum(array_column($oldClearedOrderAgent, 'settlementMaterial_usage')));
        //人工费
        $OldOrder_for_reality_artificial = sprintf('%.2f', array_sum(array_column($oldClearedOrderMan, 'capitalPersonal')));
        $annualProportion = 0;
        if ($end >= 1704038399 && $settlementEndOfPayment['agencyMoney'] + $EndOfPayment['MainMaterialMoney'] != 0) {
            $annualProportion = (($OldEndOfPaymentMan['MainMaterialMoney'] + $OldEndOfPaymentAgent['agencyMoney']) / ($settlementEndOfPayment['agencyMoney'] + $EndOfPayment['MainMaterialMoney']));
        }

        //2024年结算的
        //材料报销
        $material_usage = sprintf('%.2f', array_sum(array_column($clearedOrder, 'material_usage'))) - $OldMaterial_usage;
        //报销费用
        $reimbursement            = sprintf('%.2f', array_sum(array_column($clearedOrder, 'reimbursement'))) - $OldReimbursement;
        $settlementReimbursement  = sprintf('%.2f', array_sum(array_column($settlementOrder, 'settlementReimbursement'))) - $OldSettlementReimbursement;
        $settlementMaterial_usage = sprintf('%.2f', array_sum(array_column($settlementOrder, 'settlementMaterial_usage'))) - $OldSettlementMaterial_usage;
        //人工费
        $order_for_reality_artificial = sprintf('%.2f', array_sum(array_column($clearedOrder, 'capitalPersonal'))) - $OldOrder_for_reality_artificial;
        //项目利润
        $oldSum = 0;
        $moneyrFee = $money;
        if ($end <= 1704038399) {
            $oldList = [];
            $totalMoney = $EndOfPayment['MainMaterialMoney'] - $order_for_reality_artificial - $material_usage - $reimbursement - (string)round($money * $discountRate, 2);
            $discountRateProfit = (string)round($money * $discountRate, 2);
            $oldMoney = $money * $discountRate;
        } else {
            $discountRateProfit = (string)round((($money * $discountRate) * (1 - $annualProportion)), 2);
            $EndOfPayment['MainMaterialMoney'] = $EndOfPayment['MainMaterialMoney'] - $OldEndOfPaymentMan['MainMaterialMoney'];
            $settlementEndOfPayment['agencyMoney'] = $settlementEndOfPayment['agencyMoney'] - $OldEndOfPaymentAgent['agencyMoney'];
            $totalMoney = $EndOfPayment['MainMaterialMoney'] - $order_for_reality_artificial - $material_usage - $reimbursement - $discountRateProfit - (string)($EndOfPayment['MainMaterialMoney'] * 0.05);
            $oldMoney = $money * $discountRate;
            $money = round($money * $discountRate, 2);
        }
        //2024项目基数
        if (!empty($EndOfPayment['MainMaterialMoney']) && $EndOfPayment['MainMaterialMoney'] > 0) {
            $base = sprintf('%.4f', ($EndOfPayment['MainMaterialMoney'] - $order_for_reality_artificial - $material_usage - $reimbursement - (string)($EndOfPayment['MainMaterialMoney'] * 0.05)) / $EndOfPayment['MainMaterialMoney']);
        } else {
            $base = 0;
        }
        $baseNumber = $this->manBase($start, $base);
        $baseNumber1 = $this->agenBase($start, $base);

        //老的项目基数
        if (!empty($OldEndOfPaymentMan['MainMaterialMoney']) && $OldEndOfPaymentMan['MainMaterialMoney'] > 0) {
            $base1 = sprintf('%.4f', ($OldEndOfPaymentMan['MainMaterialMoney'] - $OldOrder_for_reality_artificial - $OldMaterial_usage - $OldReimbursement) / $OldEndOfPaymentMan['MainMaterialMoney']);
        } else {
            $base1 = 0;
        }
        $oldBaseNumber = $this->OldManBase($start, $base1);
        $oldBaseNumber1 = $this->agenBase($start, $base1);

        //分红比例
        $aBonus               = self::aBonus($induction_time, $id, $start, $end, $type);
        $conversion = $aBonus['conversion'];
        $aBonus['conversion'] = sprintf('%.3f', $conversion * $baseNumber);
        $aBonus['conversion1'] = sprintf('%.3f', $conversion * $oldBaseNumber);
        $agencyMoneyProfit = 0;
        $oldSumtotalMoney = 0;
        $agencyMoney = 0;
        $direct_commission_rati=0;
        if ($end > 1704038399) {
            $oldSumtotalMoney = (string)round($OldEndOfPaymentMan['MainMaterialMoney'] - $OldOrder_for_reality_artificial - $OldMaterial_usage - $OldReimbursement - (string)round($oldMoney - $discountRateProfit, 2), 2);
            $oldSum = (string)round($oldSumtotalMoney * $aBonus['conversion1'], 2) + (string)round(($OldEndOfPaymentAgent['agencyMoney'] - $OldSettlementMaterial_usage - $OldSettlementReimbursement) * $oldBaseNumber1, 2);
            $agencyMoneyProfit = sprintf('%.2f', $OldEndOfPaymentAgent['agencyMoney'] - $OldSettlementMaterial_usage - $OldSettlementReimbursement);
            $agencyMoney = $agencyMoneyProfit * 0.1;
        }
        return (['CommissionAmount' => sprintf('%.2f', $totalMoney * $aBonus['conversion'] + ($settlementEndOfPayment['agencyMoney'] - $settlementReimbursement - $settlementMaterial_usage) * $baseNumber1), 'ProjectProfitList' => [
            'MainMaterialMoney' => (string)$EndOfPayment['MainMaterialMoney'],
            'orderForRealityArtificial' => $order_for_reality_artificial,
            'materialUsage' => $material_usage,
            'reimbursement' => $reimbursement,
            'companyCommission' => 0,
            'money' => round($moneyrFee - ($moneyrFee * $annualProportion), 2),
            'discountRate' => $discountRateProfit . '(' . round($discountRate * 100, 2) . '%)',
            'thisMonthTargetPerformance' => 0, //本月已接单目标业绩
            'onlineAchievement' => 0, //查线当月实际业绩
            'orderAttributionsAmount' => 0, //业绩目标超额奖金
            'orderAttributionsDeductAmount' => 0, //未达业绩目标扣除商机成本
             'direct_commission_rati'=>$direct_commission_rati,
            'cost' => 0, //订单成本
            'order_attributions_70_amount' => 0,
            'order_attributions_30_amount' => 0,
            'companyCommission_year'=>0,
            'delay_deduct_amount'=>0,
            'delay_tui_amount'=>0,
            'approval_schedule_liability_amount'=>0
        ], 'ProjectProfit' => sprintf('%.2f', $totalMoney), 'base' => $baseNumber, 'baseNumber' => $base, 'aBonus' => $aBonus['conversion'], 'conversion' => $aBonus['aBonus'], 'agencyMoney' => sprintf('%.2f', ($settlementEndOfPayment['agencyMoney'] - $settlementReimbursement - $settlementMaterial_usage) * 0.1), 'agencyMoneyProfit' => sprintf('%.2f', $settlementEndOfPayment['agencyMoney'] - $settlementReimbursement - $settlementMaterial_usage), 'username' => $username, 'discountRate' => $discountRate, 'orderId' => implode(',', array_unique(array_merge($newOrderIdAgent, $newOrderIdMan))), 'oldSum' => $oldSum, 'oldList' => [['CommissionAmount' => $oldSum, 'ProjectProfitList' => [
            'MainMaterialMoney' => $OldEndOfPaymentMan['MainMaterialMoney'],
            'orderForRealityArtificial' => $OldOrder_for_reality_artificial,
            'materialUsage' => $OldMaterial_usage,
            'reimbursement' => $OldReimbursement,
            'money' => round($moneyrFee * $annualProportion, 2),
            'discountRate' => (string)round($oldMoney - $discountRateProfit, 2) . '(' . round($discountRate * 100, 2) . '%)',
            'thisMonthTargetPerformance' => 0, //本月已接单目标业绩
            'onlineAchievement' =>  0, //查线当月实际业绩
            'orderAttributionsAmount' =>  0, //业绩目标超额奖金
            'orderAttributionsDeductAmount' =>  0, //未达业绩目标扣除商机成本
            'cost' => 0, //订单成本
            'orderAttributions70Amount' => 0,
            'orderAttributions30Amount' => 0,
            'companyCommission_year'=>0,
            'delay_deduct_amount'=>0,
            'delay_tui_amount'=>0,
            'approval_schedule_liability_amount'=>0
        ], 'ProjectProfit' => sprintf('%.2f', $oldSumtotalMoney), 'base' => $oldBaseNumber, 'baseNumber' => $base1, 'aBonus' => $aBonus['conversion1'], 'conversion' => $aBonus['aBonus'], 'agencyMoney' => sprintf('%.2f', $agencyMoney), 'agencyMoneyProfit' => $agencyMoneyProfit, 'username' => $username, 'discountRate' => $discountRate, 'orderId' => implode(',', array_unique(array_merge($oldClearedOrderManOrderId, $oldClearedOrderAgentOrderId))),]]]);
    }
    /*
 * 储备店长总数据
 */
    public function NewReserveManager($induction_time, $start, $end, $type, $id, $username = '')
    {
        $sysConfig = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->where('statusss', 1)->value('valuess');
        $order     = \db('order')
            ->field('order_aggregate.reimbursement_price as reimbursement,order_aggregate.reimbursement_agent_price as settlementReimbursement,order_aggregate.material_price as material_usage,order.order_id,order.cleared_time,order.settlement_time,order.created_time,order.notcost_time, order_aggregate.master_price as capitalPersonal,contract.con_time, order_aggregate.material_agent_price as settlementMaterial_usage,order.attributions,order_times.change_work_time')
            ->join('user', 'user.user_id=order.assignor', 'left')
            ->join('order_times', 'order_times.order_id=order.order_id', 'left')
            ->join('contract', 'contract.orders_id=order.order_id', 'left')
            ->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left');
        if ($type == 1) {
            $order->where('user.user_id', $id);
        } elseif ($type == 2) {
            $order->where('user.store_id', $id);
        }
        if ($induction_time > $start) {
            $start = $induction_time;
        }
        $orderList = $order->where(function ($quer) use ($start, $end) {
            $quer->whereBetween('order.cleared_time', [$start, $end])->whereOr('order.settlement_time', 'between', [$start, $end]);
        })->where('contract.con_time', '>', $induction_time)->where('user.ce', '<>', 2)->group('order.order_id')->select();

        $clearedOrder       = [];
        $settlementOrder    = [];
        $daSettlementOrder    = [];

        $_main_discount_amount = 0;
        $_agent_discount_amount = 0;
        $_da_agent_discount_amount = 0;
        foreach ($orderList as $item) {
            if (!empty($item['cleared_time']) && ($start <= $item['cleared_time'] && $end >= $item['cleared_time'])) {
                $clearedOrder[] = $item;
            }
            if (!empty($item['settlement_time']) && ($start <= $item['settlement_time'] && $end >= $item['settlement_time']) && $item['attributions'] != 2) {
                $settlementOrder[] = $item;
            }
            if (!empty($item['settlement_time']) && ($start <= $item['settlement_time'] && $end >= $item['settlement_time']) && $item['attributions'] == 2) {
                $daSettlementOrder[] = $item;
            }
            if (!empty($item['cleared_time']) && $item['cleared_time'] > 1732982400 && ($start <= $item['cleared_time'] && $end >= $item['cleared_time'])) {
                $_main_discount_amount += db('approval_record', config('database.zong'))->whereIn("order_id", $item['order_id'])->where("type", 2)->where('status', 1)->where('created_time', '>', $item['change_work_time'])->sum('change_value');
            };

            if (!empty($item['settlement_time']) && $item['settlement_time'] > 1732982400 && ($start <= $item['settlement_time'] && $end >= $item['settlement_time']) && $item['attributions'] != 2) {
                $_agent_discount_amount += db('approval_record', config('database.zong'))->whereIn("order_id", $item['order_id'])->where("type", 3)->where('status', 1)->where('created_time', '>', $item['change_work_time'])->sum('change_value');
            }
            if (!empty($item['settlement_time']) && $item['settlement_time'] > 1732982400 &&  ($start <= $item['settlement_time'] && $end >= $item['settlement_time']) && $item['attributions'] == 2) {
                $_da_agent_discount_amount += db('approval_record', config('database.zong'))->whereIn("order_id", $item['order_id'])->where("type", 3)->where('status', 1)->where('created_time', '>', $item['change_work_time'])->sum('change_value');
            }
        }
        $order_id           = array_column($clearedOrder, 'order_id');
        $settlementOrder_id = array_column($settlementOrder, 'order_id');
        $daSettlementOrder_id = array_column($daSettlementOrder, 'order_id');
        // 完款金额
        $EndOfPayment           = (new OrderModel())->TotalProfit($order_id);
        $settlementEndOfPayment = (new OrderModel())->TotalProfit($settlementOrder_id);
        //大ka
        $daSettlementEndOfPayment = (new OrderModel())->TotalProfit($daSettlementOrder_id);

        //2024年结算的
        //材料报销
        $material_usage = sprintf('%.2f', array_sum(array_column($clearedOrder, 'material_usage')) + array_sum(array_column($settlementOrder, 'settlementMaterial_usage')) + array_sum(array_column($daSettlementOrder, 'settlementMaterial_usage')));
        //报销费用
        $reimbursement            = sprintf('%.2f', array_sum(array_column($clearedOrder, 'reimbursement')) + array_sum(array_column($settlementOrder, 'settlementReimbursement')) + array_sum(array_column($daSettlementOrder, 'settlementReimbursement')));
        //人工费
        $order_for_reality_artificial = sprintf('%.2f', array_sum(array_column($clearedOrder, 'capitalPersonal')));

        //总共金额
        $MainMaterialMoney = (string)(bcsub($EndOfPayment['MainMaterialMoney'],$EndOfPayment['manZhiShou'],2) + bcsub($settlementEndOfPayment['agencyMoney'],$settlementEndOfPayment['daiZhiShou'],2) + bcsub($daSettlementEndOfPayment['agencyMoney'],$daSettlementEndOfPayment['daiZhiShou'],2));
        //公司提成
        $companyCommission = (string)(round((bcsub($EndOfPayment['MainMaterialMoney'],$EndOfPayment['manZhiShou'],2) + $_main_discount_amount) * 0.33, 2) + round(($settlementEndOfPayment['agencyMoney'] + $_agent_discount_amount) * 0.23, 2) + round(($daSettlementEndOfPayment['agencyMoney'] + $_da_agent_discount_amount) * 0.26, 2));
        $thisMonthTargetPerformance = 0;
        $orderAttributionsAmount = 0;
        $orderAttributionsDeductAmount = 0;
        $onlineAchievement = 0;
        $order_attributions_70_amount = 0;
        $order_attributions_30_amount = 0;
        $cost = 0;
        $companyCommission_year=0;
        $delay_deduct_amount=0;
        $delay_tui_amount=0;
        $approval_schedule_liability_amount=0;
        $direct_commission_rati=0;
        $direct_shopowner_profit=0;
        if ($start >= 1738339200) {
            $ends = $end;
            if (date('Ym', $end) == date('Ym', time())) {
                $ends = time();
            }
           if ($type == 1) {
                $store_shopowner_commission = db('store_shopowner_commission', config('database.zong'))->where('user_id', $id)->where('count_day', date('Ymd', $ends))->find();
            } elseif ($type == 2) {
                $store_shopowner_commission = db('store_shopowner_commission', config('database.zong'))->where('store_id', $id)->where('count_day', date('Ymd', $ends))->find();
            }
            $companyCommission = $store_shopowner_commission['agent_company_commission_amount'] + $store_shopowner_commission['main_company_commission_amount'];
            if($start >= 1746028800){
                $companyCommission = $store_shopowner_commission['main_capital_channel_commission'] + $store_shopowner_commission['main_capital_company_commission']+$store_shopowner_commission['agent_capital_channel_commission'] + $store_shopowner_commission['agent_capital_company_commission'];
            }
            //直售提成金额
            $direct_commission_rati=$store_shopowner_commission['direct_commission_money'] ;
            //直售固定提成
             $direct_shopowner_profit=$store_shopowner_commission['main_direct_shopowner_cost']+$store_shopowner_commission['agent_direct_shopowner_cost'];
            //年度绩效金存入(1%)
            $companyCommission_year = (string)round(($store_shopowner_commission['agent_cleared_amount']+$store_shopowner_commission['agent_discount_amount'] + $store_shopowner_commission['main_cleared_amount']+$store_shopowner_commission['main_discount_amount'])*0.01,2);
            //延期暂扣款
           
            $allowOride=array_merge(array_merge($order_id,$settlementOrder_id),$daSettlementOrder_id);
            $deduction_money=db('order_delay_deduction_commission', config('database.zong'))->whereIn('order_id', $allowOride)->where('deduction_state', 1)->where('date_month', date('Ym', $ends))->where('delete_time',0)->sum('deduction_money');
            $delay_deduct_amount=empty( $deduction_money)?0:$deduction_money;
           
           //延期暂扣款退回
           $refund_deduction_money=db('order_delay_deduction_commission', config('database.zong'))->whereIn('order_id', $allowOride)->where('refund_state', 1)->where('refund_month', date('Ym', $ends))->where('delete_time',0)->sum('deduction_money');
           $delay_tui_amount=empty( $refund_deduction_money)?0: $refund_deduction_money;
            $order_attributions_data_list = json_decode($store_shopowner_commission['order_attributions_data_list'], true);
            if(!empty($order_attributions_data_list)){
                foreach ($order_attributions_data_list as $key => $value) {
                    if ($value['id'] == 'achievement') {
                        $thisMonthTargetPerformance = $value['data'];
                    }
                    if ($value['id'] == 'order_attributions_amount') {
                        $orderAttributionsAmount = $value['data'];
                    }
                   
                    if ($value['id'] == 'online_achievement') {
                        $onlineAchievement = $value['data'];
                    }
                    if ($value['id'] == 'cost') {
                        $cost = $value['data'];
                    }
                }
            }
            $orderAttributionsDeductAmount = $store_shopowner_commission['order_attributions_deduct_amount_current'];
            $order_attributions_70_amount = $store_shopowner_commission['order_attributions_amount_current'];
            $order_attributions_30_amount = bcsub($store_shopowner_commission['order_attributions_amount'] , $store_shopowner_commission['order_attributions_amount_current'],2);
            $approval_schedule_liability_amount= $store_shopowner_commission['approval_schedule_liability_amount'];
        }
        //利润
        $totalMoney = $MainMaterialMoney - $order_for_reality_artificial - $material_usage - $reimbursement;
        $CommissionAmount = $MainMaterialMoney - $order_for_reality_artificial - $material_usage - $reimbursement - $companyCommission + $order_attributions_70_amount - $orderAttributionsDeductAmount-$companyCommission_year-$delay_deduct_amount+$delay_tui_amount-$approval_schedule_liability_amount+$direct_commission_rati+$direct_shopowner_profit;
        return ([
            'CommissionAmount' => sprintf('%.2f', $CommissionAmount),
            'ProjectProfitList' => [
                'MainMaterialMoney' => $MainMaterialMoney,
                'orderForRealityArtificial' => $order_for_reality_artificial,
                'materialUsage' => $material_usage,
                'reimbursement' => $reimbursement,
                'money' => 0,
                'companyCommission' => empty($companyCommission)?0:$companyCommission,//公司提成
                'discountRate' => 0,
                'thisMonthTargetPerformance' => empty($thisMonthTargetPerformance)?0:$thisMonthTargetPerformance, //本月已接单目标业绩
                'onlineAchievement' => empty($onlineAchievement)?0:$onlineAchievement, //查线当月实际业绩
                'orderAttributionsAmount' => empty($orderAttributionsAmount)?0:$orderAttributionsAmount, //业绩目标超额奖金
                'orderAttributionsDeductAmount' => empty($orderAttributionsDeductAmount)?0:$orderAttributionsDeductAmount, //未达业绩目标扣除商机成本
                'direct_commission_rati'=>$direct_commission_rati,
                'direct_shopowner_profit'=>$direct_shopowner_profit,
                'cost' => $cost, //订单成本
                'order_attributions_70_amount' => empty($order_attributions_70_amount)?0:$order_attributions_70_amount,
                'order_attributions_30_amount' => empty($order_attributions_30_amount)?0:$order_attributions_30_amount,
                'companyCommission_year'=>empty($companyCommission_year)?0:$companyCommission_year,
                'delay_deduct_amount'=>empty($delay_deduct_amount)?0:$delay_deduct_amount,
                'delay_tui_amount'=>empty($delay_tui_amount)?0:$delay_tui_amount,
                'approval_schedule_liability_amount'=>empty($approval_schedule_liability_amount)?0:$approval_schedule_liability_amount,
            ],
            'ProjectProfit' => sprintf('%.2f', $totalMoney),
            'base' => 0,
            'baseNumber' => 0,
            'aBonus' => 0,
            'conversion' => 0,
            'agencyMoney' => 0,
            'agencyMoneyProfit' => 0,
            'username' => $username,
            'discountRate' => 0,
            'orderId' => implode(',', array_unique(array_merge($order_id, $settlementOrder_id))),
            'oldSum' => 0,
            'oldList' => null
        ]);
    }

    /*
     * 计算签约业绩
     */
    public function CalculatePerformance($userId, int $start_timestamp, int $end_timestamp, int $type = 1)
    {


        //当月签约的订单（排除未来的增项和添加未来的减项），
        $list = db('order')->alias('order');
        $list->join('order_info', 'order.order_id=order_info.order_id', 'left');
        $list->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left');
        $list->join('user user', 'user.user_id=order.assignor', 'left');
        $list->join('order_achievement', 'order_achievement.order_id = order.order_id', 'left');
        $list->whereBetween('order_achievement.assert_time', [$start_timestamp, $end_timestamp]);
        $list->whereIn('order_achievement.achievement_type', [1, 2]);
        $list->where('user.user_id', $userId);
        if ($type == 2) {
            $list->where('order.hematopoiesis', '<>', 1);
        }
        //        $list->where('order.state', '>', 3);
        //        $list->where('order.state', '<', 8);
        $list->where('user.ce', '=', 1);
        $list->where('order_achievement.delete_time', '=', 0);
        $list->field('order.order_id,order.contacts,
        concat(order_info.province,order_info.city,order_info.county,order.addres) as addres,
        order_aggregate.reimbursement_price as agency_sum,
        order_aggregate.master_price as estimate,
        order_aggregate.material_price as MaterialBudget,
        round((sum(order_achievement.assert_money) -order_aggregate.master_price-(order_aggregate.material_price+order_aggregate.material_agent_price)-order_aggregate.agent_price-order_aggregate.reimbursement_price),2) as profit,
   order_info.pro_id_title as title,
                     order.quarters_id,
                        order.pro_id,
                        FROM_UNIXTIME(order_achievement.assert_time,"%Y-%m-%d %H-%i" ) as con_time,
                        round(sum(order_achievement.assert_money),2) as amount');
        $list->group('order.order_id');
        $data = $list->select();
        return empty($data) ? [] : $data;
    }

    /*
    * 计算业绩
    */
    public function RCalculatePerformance($userId, int $start_timestamp, int $end_timestamp, int $type = 1)
    {
        //当月签约的订单（排除未来的增项和添加未来的减项），
        $list = db('order')->alias('order');
        $list->join('user user', 'user.user_id=order.assignor', 'left');
        $list->join('order_achievement', 'order_achievement.order_id = order.order_id', 'left');
        $list->whereBetween('order_achievement.assert_time', [$start_timestamp, $end_timestamp]);
        $list->where('user.user_id', $userId);
        if ($type == 2) {
            $list->where('order.hematopoiesis', '<>', 1);
        }
        //        $list->where('order.state', '>', 3);
        //        $list->where('order.state', '<', 8);
        $list->where('user.ce', '=', 1);
        $list->where('order_achievement.delete_time', '=', 0);
        $data = $list->sum('assert_money');
        return empty($data) ? [] : $data;
    }
    /*
     * 主合同基数
     */
    public function manBase($start, $base)
    {
        if (1625068800 > $start) {
            if ($base >= 0.45) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.44 && $base < 0.45) {
                //B级
                $baseNumber = 0.9;
            } elseif ($base >= 0.43 && $base < 0.44) {
                //C级
                $baseNumber = 0.8;
            } elseif ($base >= 0.42 && $base < 0.43) {
                //C级
                $baseNumber = 0.7;
            } elseif ($base >= 0.41 && $base < 0.42) {
                //C级
                $baseNumber = 0.6;
            } elseif ($base >= 0.40 && $base < 0.41) {
                //C级
                $baseNumber = 0.5;
            } elseif ($base >= 0.39 && $base < 0.40) {
                //C级
                $baseNumber = 0.4;
            } elseif ($base >= 0.38 && $base < 0.39) {
                //C级
                $baseNumber = 0.3;
            } elseif ($base >= 0.37 && $base < 0.38) {
                //C级
                $baseNumber = 0.2;
            } elseif ($base >= 0.36 && $base < 0.37) {
                //C级
                $baseNumber = 0.1;
            } else {
                //D级
                $baseNumber = 0;
            }
        } elseif (1625068800 < $start && 1704038400 > $start) {
            if ($base >= 0.45) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.40 && $base < 0.45) {
                //B级
                $baseNumber = 0.8;
            } elseif ($base >= 0.35 && $base < 0.40) {
                //C级
                $baseNumber = 0.5;
            } else {
                //D级
                $baseNumber = 0;
            }
        } else {
            if ($base >= 0.40) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.35 && $base < 0.40) {
                //B级
                $baseNumber = 0.8;
            } elseif ($base >= 0.30 && $base < 0.35) {
                //C级
                $baseNumber = 0.5;
            } else {
                //D级
                $baseNumber = 0;
            }
        }
        return $baseNumber;
    }
    /*
   * 主合同基数
   */
    public function oldManBase($start, $base)
    {
        if (1625068800 > $start) {
            if ($base >= 0.45) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.44 && $base < 0.45) {
                //B级
                $baseNumber = 0.9;
            } elseif ($base >= 0.43 && $base < 0.44) {
                //C级
                $baseNumber = 0.8;
            } elseif ($base >= 0.42 && $base < 0.43) {
                //C级
                $baseNumber = 0.7;
            } elseif ($base >= 0.41 && $base < 0.42) {
                //C级
                $baseNumber = 0.6;
            } elseif ($base >= 0.40 && $base < 0.41) {
                //C级
                $baseNumber = 0.5;
            } elseif ($base >= 0.39 && $base < 0.40) {
                //C级
                $baseNumber = 0.4;
            } elseif ($base >= 0.38 && $base < 0.39) {
                //C级
                $baseNumber = 0.3;
            } elseif ($base >= 0.37 && $base < 0.38) {
                //C级
                $baseNumber = 0.2;
            } elseif ($base >= 0.36 && $base < 0.37) {
                //C级
                $baseNumber = 0.1;
            } else {
                //D级
                $baseNumber = 0;
            }
        } else {
            if ($base >= 0.45) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.40 && $base < 0.45) {
                //B级
                $baseNumber = 0.8;
            } elseif ($base >= 0.35 && $base < 0.40) {
                //C级
                $baseNumber = 0.5;
            } else {
                //D级
                $baseNumber = 0;
            }
        }
        return $baseNumber;
    }
    /*
    * 代购同基数
    */
    public function agenBase($start, $base)
    {
        $baseNumber1 = 0.1;
        if (1640966400 <= $start) {

            if ($base >= 0.45) {
                //A级
                $baseNumber = 1;
            } elseif ($base >= 0.40 && $base < 0.45) {
                //B级
                $baseNumber = 0.8;
            } elseif ($base >= 0.35 && $base < 0.40) {
                //C级
                $baseNumber = 0.5;
            } else {
                //D级
                $baseNumber = 0;
            }
            $baseNumber1 = 0.1;
        }
        return $baseNumber1;
    }
    /**
     * 获取公司计提比例
     */
    public function getcityLevelAchievementCost()
    {
        return [
            241 => ['AA' => ['achievement' => 6000, 'cost' => 600], 'A' => ['achievement' => 6000, 'cost' => 600], 'B' => ['achievement' => 4500, 'cost' => 400], 'C' => ['achievement' => 2000, 'cost' => 200]],
            239 => ['AA' => ['achievement' => 6000, 'cost' => 600], 'A' => ['achievement' => 6000, 'cost' => 600], 'B' => ['achievement' => 4500, 'cost' => 400], 'c' => ['achievement' => 2000, 'cost' => 200]],
            172 => ['AA' => ['achievement' => 6000, 'cost' => 600], 'A' => ['achievement' => 6000, 'cost' => 600], 'B' => ['achievement' => 4500, 'cost' => 400], 'c' => ['achievement' => 2000, 'cost' => 200]],
            262 => ['AA' => ['achievement' => 6000, 'cost' => 600], 'A' => ['achievement' => 6000, 'cost' => 600], 'B' => ['achievement' => 4500, 'cost' => 400], 'c' => ['achievement' => 2000, 'cost' => 200]],
            375 => ['AA' => ['achievement' => 8000, 'cost' => 800], 'A' => ['achievement' => 8000, 'cost' => 800], 'B' => ['achievement' => 6000, 'cost' => 600], 'c' => ['achievement' => 2000, 'cost' => 200]],
            202 => ['AA' => ['achievement' => 8000, 'cost' => 800], 'A' => ['achievement' => 8000, 'cost' => 800], 'B' => ['achievement' => 6000, 'cost' => 600], 'c' => ['achievement' => 2000, 'cost' => 200]],
            501 => ['AA' => ['achievement' => 8000, 'cost' => 800], 'A' => ['achievement' => 8000, 'cost' => 800], 'B' => ['achievement' => 6000, 'cost' => 600], 'c' => ['achievement' => 2000, 'cost' => 200]],
            200 => ['AA' => ['achievement' => 8000, 'cost' => 800], 'A' => ['achievement' => 8000, 'cost' => 800], 'B' => ['achievement' => 6000, 'cost' => 600], 'c' => ['achievement' => 2000, 'cost' => 200]],
            205 => ['AA' => ['achievement' => 6000, 'cost' => 600], 'A' => ['achievement' => 6000, 'cost' => 600], 'B' => ['achievement' => 4500, 'cost' => 400], 'c' => ['achievement' => 2000, 'cost' => 200]],
            216 => ['AA' => ['achievement' => 6000, 'cost' => 600], 'A' => ['achievement' => 6000, 'cost' => 600], 'B' => ['achievement' => 4500, 'cost' => 400], 'c' => ['achievement' => 2000, 'cost' => 200]],
        ];
    }
    /**
     * 扣除
     */
    public function pricingOfBusinessOpportunityCosts($user_id, $begin, $end)
    {
        //商机等级进行商机业绩标准和商机成本的定价
        $ratio = $this->getcityLevelAchievementcost();
        $city_ratio = $ratio[config('cityId')];
        //dd($ratio):
        //dd($ratio[$city['city_code']]):
        //线上渠道业绩目标超额奖金和未达目标成本扣除
        //目标业绩和成本计算
        $over_limit_bonus = db('order')
            ->join('order_times', 'order_times.order_id=order.order_id', 'left')
            ->join('channel_level', 'channel_level.chanel_id=order.channel_details and channel_level.goods_category_1_id=order.pro_id and channel_level.goods_category_2_id=order.pro_id1', 'left')
            ->where('order.assignor', $user_id)
            //->where('order_times.dispatch_time','between',[$begin,$end])//按派单时间筛选当月订单
            ->where(function ($query) use ($begin, $end) {
                $query->whereBetween('order_times.dispatch_time', [$begin, $end])->whereOr('order_times.change_work_time', 'between', [$begin, $end]); //按派单时间筛选当月订单
            })
            ->where('order.attributions', 1) //线上渠道
            ->where('order.state', '>', 0)
            ->where('order.state', '<', 10) //排除无效单
            ->field('order.order_id,order.attributions,order.assignor, order.state,order.tui_time,order_times.dispatch_time, order_times.change_work_time,channel_level.level')
            ->select();
        $achievement = 0;
        $cost = 0;
        //10单以上
        $order_num = 0;
        $order_deal_num = 0;
        //成交率25%及以上
        $order_rate = 100; //默认100%
        $participate_in = false;
        if (count($over_limit_bonus) > 0) {
            foreach ($over_limit_bonus as $k => $v) {
                //派单时间在时间范围内，排除无效单
                if (intval($v['dispatch_time']) >= $begin && intval($v['dispatch_time']) <= $end && intval($v['state']) != 10) {
                    $achievement += isset($city_ratio[$v['level']]['achievement']) ? $city_ratio[$v['level']]['achievement'] : 0;
                    $cost += isset($city_ratio[$v['level']]['cost']) ? $city_ratio[$v['level']]['cost'] : 0;
                    $order_num++;
                }
                //正签时间在时间范围内，
                if (intval($v['change_work_time']) >= $begin && intval($v['change_work_time']) <= $end) {
                    //当月签当月退的不计算成交
                    if (!(intval($v['state']) == 9 && intval($v['tui time']) > 0 && intval($v['tui time']) <= $end)) {
                        $order_deal_num++;
                    }
                }
            }
        }

        if ($order_num > 0) {
            $order_rate = round($order_deal_num / $order_num * 100, 2);
        }
        //参与条件:10单及以上，成交率25%及以上
        if ($order_num >= 10 && $order_rate >= 25) {
            $participate_in = true;
        }

        //查线上渠道当月实际业绩
        $online_achievement = db('order')->join('order_achievement a', 'a.order_id=order.order_id', 'left')->where('order.assignor', '=', $user_id)
            ->where("a.assert_time", "between", [$begin, $end]) //业绩生效时间
            ->where("order.attributions", 1) //线上渠道
            ->where("a.delete_time", 0) //没有删除
            ->sum('assert_money');
        $order_attributions_amount = 0; //线上渠道业绩目标超额奖金
        $order_attributions_deduct_amount = 0; //线上渠道未达业绩目标扣除商机成本
        $excess_performance = 0; //超额业绩
        $failed_to_achieve_performance = 0; //未达成业绩
        //判断业绩达成率
        if ($achievement > 0) {
            //实际业绩达成率=实际业绩÷目标业绩
            $round_ratio = round($online_achievement / $achievement * 100, 5);
            $excess_performance = abs($achievement - $online_achievement);
            if ($round_ratio < 100) {
                //未实现目标业绩，需要承担商机成本 100%

                $order_attributions_deduct_amount = Round($cost * ($excess_performance / $achievement), 2);

                $failed_to_achieve_performance = $achievement - $online_achievement;
            } elseif ($round_ratio > 100 && $round_ratio <= 150 && $participate_in) { //实际业绩达成率超过商机目标业绩 50%以内，执行超额业绩部分*6%的业绩提成奖金;
                $order_attributions_amount = round(($online_achievement - $achievement) * 0.06, 2);
            } elseif ($round_ratio > 150 && $participate_in) {
                //实际业纬达成率超过商机目标业绩 50%以上，执行超额业纬部分*8%的业绩提成奖金
                $order_attributions_amount = round(($online_achievement - $achievement) * 0.08, 2);
            }
        }

        $order_attributions_amount = 0;
        return ['order_attributions_amount' => $order_attributions_amount, 'order_attributions_deduct_amount' => $order_attributions_deduct_amount, 'online_achievement' => $online_achievement, 'achievement' => $achievement, 'excess_performance' => $excess_performance, 'failed_to_achieve_performance' => $failed_to_achieve_performance, 'order_num' => $order_num, 'order_rate' => $order_rate];
    }

    public function ReserveManagerInfo(){
        $param = Authority::param(['startTime', 'userId', 'type']);
        $type=$param['type'];
        if($param['type']==10){
            $type=9;
        }
        $user     = \db('user')->where('user_id',$param['userId'])->find();
        $Llsit=[
            array(
                'title'=>'主合同结算金额',
                'act'=>'reserve_main',
                'type'=>1
                
            ),
            array(
                'title'=>' └─>主合同计提',
                'act'=>'main_company_commission',
                'type'=>5
            ),

            array(
                'title'=>' └─人工费用',
                'act'=>'reserve_store_cost_master',
                'type'=>2
            ),
            array(
                'title'=>' └─材料费用',
                'act'=>'reserve_material',
                'type'=>3
            ),
            array(
                'title'=>' └─报销费用',
                'act'=>'reserve_cost',
                'type'=>4
            ),
            array(
                'title'=>'代购合同结算金额',
                'act'=>'reserve_agent',
                'type'=>1
            ),
            array(
                'title'=>' └─代购合同计提',
                'act'=>'agent_company_commission',
                'type'=>5
            ),
            array(
                'title'=>' └─主材请款',
                'act'=>'reserve_material_cost',
                'type'=>4
            ),
            array(
                'title'=>' └─主材领用',
                'act'=>'agent_reserve_material',
                'type'=>3
            ),
            array(
                'title'=>'主合同店长年度绩效',
                'act'=>'main_user_commission',
                'type'=>8
            ),
            array(
                'title'=>'代购店长年度绩效',
                'act'=>'agent_user_commission',
                'type'=>8
            ),
            array(
                'title'=>'主合同延期扣款与退款',
                'act'=>'main_delay_deduct_amount',
                'type'=>9
            ),
            array(
                'title'=>'代购延期扣款与退款',
                'act'=>'agent_delay_deduct_amount',
                'type'=>9
            ),
            array(
                'title'=>'C端超额业绩提成',
                'act'=>'order_attributions_amount',
                'type'=>6
            ),
            array(
                'title'=>'C端承担商机成本',
                'act'=>'order_attributions_deduct_amount',
                'type'=>7
            ),
            array(
                'title'=>'审批时责任划分承担金额',
                'act'=>'approval_schedule_liability_amount',
                'type'=>11
            )
            ];
            $arr   = date_parse_from_format('Y年m月', $param['startTime']);
            $time = mktime(0, 0, 0, $arr['month'], 01, $arr['year']);
            $limit=isset($param['limit'])?$param['limit']:50;
            $p=isset($param['p'])?$param['p']:1;
            //请求数据
            $requestData=[];
            foreach($Llsit as $item){
                if($type==$item['type']){
                    $listData=detailedListOfDividends($item['act'], $param['userId'],$user['store_id'], $time,$limit,$p);
                    if($listData['code']==200){
                        $requestData[]=isset($listData['data']['data'])?$listData['data']['data']:[];
                    }
                    
                }
            } 
            if($type==7 || $type==6){
                foreach ($requestData as $subArray) {
                    foreach ($subArray as $order) {
                    $finalOrders[] = ['order_id' =>0,'money' => $order['money'],'title'=>$order['title'],'time'=>''];  
                    }
                }
               
                r_date(isset($finalOrders)?$finalOrders:null, 200); 
            }
            $processedOrders=[]; 
           // 遍历JSON数据中的订单数组
            foreach ($requestData as $subArray) {
                foreach ($subArray as $order) {
                    if(($param['type'] !=9 && $param['type'] !=10) || ($order['money']>0 && $param['type']==9) || ($order['money']<0 && $param['type']==10)){
                        if(isset($order['id'])){
                            // 检查$processedOrders数组中是否已存在该order_id
                        if (isset($processedOrders[$order['id'].$order['title'].$order['time']])) {
                                // 如果存在，则累加money字段
                                $processedOrders[$order['id'].$order['title'].$order['time']]['money'] += floatval($order['money']);
                            } else {
                                // 如果不存在，则将该订单添加到$processedOrders数组中，并初始化money字段
                                $processedOrders[$order['id'].$order['title'].$order['time']] = $order;
                                $processedOrders[$order['id'].$order['title'].$order['time']]['money'] = floatval($order['money']); // 确保money是浮点数进行累加
                                // 可选：如果你只想保留order_id和money字段，可以移除其他字段
                                // unset($processedOrders[$order['order_id']]['addres'], $processedOrders[$order['order_id']]['cleared_time'], ...);
                            }
                            // 注意：这里我们保留了其他字段，但如果你不需要它们，可以在累加money后移除它们
                        }
                    }
           
                }
        
            }
          
            // 将处理后的订单数据转换回只包含order_id和累加后的money的数组（如果需要的话）
            $finalOrders = [];
            foreach ($processedOrders as $order) {
                 $order_id= $order['id'];
                if($order['url'] !='order'){
                    $order_id= 0;
                    if($param['type']==11){
                        $order_id= $order['order_id'];
                    }
                }
                if($param['type']==10 && $order['money']<=0){
                  $finalOrders[] = ['order_id' =>$order_id,'money' => $order['money'],'title'=>$order['title'],'time'=>$order['time']];
                }elseif($param['type']==9 && $order['money']>=0){
                    $finalOrders[] = ['order_id' =>$order_id,'money' => $order['money'],'title'=>$order['title'],'time'=>$order['time']];
                }elseif($param['type'] !=10 && $param['type'] !=9){
                    $finalOrders[] = ['order_id' =>$order_id,'money' => $order['money'],'title'=>$order['title'],'time'=>$order['time']];  
                }
               
            }
            r_date($finalOrders, 200);
        
    }
}
